package com.openharmony.filepicker.adapter;

import com.openharmony.filepicker.ResourceTable;
import com.openharmony.filepicker.bean.FileNavBeanImpl;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.app.Context;
import java.util.ArrayList;
import java.util.List;

public class FileNavAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<FileNavBeanImpl> dataList = new ArrayList<>();

    public void setNewData(List<FileNavBeanImpl> list) {
        if (list != null) {
            dataList.clear();
            dataList.addAll(list);
            notifyDataChanged();
        }
    }

    public FileNavAdapter(Context context) {
        this.context = context;
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public FileNavBeanImpl getItem(int position) {
        if (position >= 0 && position < dataList.size()) {
            return dataList.get(position);
        }
        return null;
    }

    @Override
    public Component onCreateViewHolder(ComponentContainer parent, int viewType) {
        Component cpt = LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_item_nav_file_picker,
                        null,
                        false);
        cpt.setTag(new NavListHolder(cpt));
        return cpt;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int i,
                                  Component component,
                                  ComponentContainer componentContainer) {
        final Component cpt;
        if (component == null) {
            cpt = onCreateViewHolder(componentContainer, 0);
        } else {
            cpt = component;
        }
        NavListHolder viewHolder = (NavListHolder) cpt.getTag();
        viewHolder.bind(dataList.get(i), i);
        return cpt;
    }

    public class NavListHolder{

        private Text mBtnDir;
        private int pos;
        private Component itemView;

        public NavListHolder(Component itemView) {
            this.itemView = itemView;
        }

        public void bind(FileNavBeanImpl itemImpl, int position) {
            pos = position;
            mBtnDir = (Text) itemView.findComponentById(ResourceTable.Id_tv_btn_nav_file_picker);
            mBtnDir.setText(itemImpl.getFileName());
        }
    }

    public ArrayList<FileNavBeanImpl> getDataList() {
        return dataList;
    }

    public void setDataList(ArrayList<FileNavBeanImpl> dataList) {
        this.dataList = dataList;
    }
}
